package com.kdg.thread.consurrenttest;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock的可限时
 * @author kdg
 * @description:
 * @date 2018/5/12.
 */
public class ReentrantLockTwo implements Runnable {

    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {

        /*lock.lock();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        try {
            if(lock.tryLock(5,TimeUnit.SECONDS)){
                Thread.sleep(8000);
            }else{
                System.out.println(Thread.currentThread().getId()+" get lock is failed. ");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        ReentrantLockTwo reentrantLockTwo = new ReentrantLockTwo();
        Thread thread = new Thread(reentrantLockTwo);
        Thread thread2 = new Thread(reentrantLockTwo);
        thread.start();
        thread2.start();
    }
}
